<?php
/**
 * Created by PhpStorm.
 * User: kwibon
 * Date: 2018/11/26
 * Time: 11:18
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\api\controller\KbxToken as KbxToken;
use app\api\model\GroupToursLine as GT;
use app\api\model\Standard as SD;
use app\api\model\Trip as TripApiModel;
use app\api\model\Order as OrderModel;
use app\wap\controller\Weather as Weather;
use app\api\controller\Poi as Poi;
use think\Exception;
use think\log;
use think\Db;

class KbxOther extends Api
{
    protected $ak = "Cf0boelbhuyZGnyrSk2TtkcVgwNVB7d8";


    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');

        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    //查询全部供应商列表【包含结算账户】
    public function kbx_suppliers_list()
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/client/suppliers';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);

        return $res;
    }

    //查询全部供应商列表
    public function kbx_all_suppliers_list()
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/client/allSuppliers';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);

        return $res;
    }

    //根据城市查询供应商列表
    public function kbx_suppliers_by_city($city_id=54)
    {
        //获取城市的mongo库ID
        $city = Db::name("city")->where("id",$city_id)->field("kbx_id")->find();
        $cityId = $city['kbx_id'];

        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/client/suppliers/listSuppliersByCityId/'.$cityId;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $res = $kbxToken->object_array($res);


        echo "<pre>";
        var_dump($res);
        echo "</pre>";
        exit;

        return $res;
    }

    //通过经纬度获取定位     调用百度Api
    public function getCountry($lat,$lng)
    {
        $url = "https://api.map.baidu.com/geocoder/v2/?extensions_poi=null&location=".$lat.",".$lng."&output=json&ak=".$this->ak;
        $kbxToken = new KbxToken();
        $res = $kbxToken->get_data($url,'');

        return $res;
    }

    //获取定制行程包车价格
    public function getCarPrice($data){
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/travelDesign/calculateDrives';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $list = json_encode($data);
        trace('核价数据：'.$list);
        $res=$kbxToken->post_data($url,$list,$token);
        trace('核价结果：'.$res);
        $this->writeCarPriceData($url,$list,$res);
        $res=$kbxToken->object_array($res);
        return $res;
    }
    //记录核价数据
    public function writeCarPriceData($url,$list,$res)
    {
        if(empty($list) || empty($url)) return false;
        $dir = APP_PATH.'logs';
        $log = 'carPrice_log';
        if(is_file($dir.'/'.$log)){
            $filesize = filesize($dir.'/'.$log);
            if($filesize>1048576){//设置log文件大小为1mb
                rename($dir.'/'.$log,$dir.'/'.$log."".date('YmdH',time()));
            }
        }
        $result = file_put_contents($dir.'/'.$log,(date('Y-m-d h:i:s',time())).'   请求地址：'.$url."\r\n".',参数：'.$list."\r\n".',结果：'.$res."\r\n",FILE_APPEND);
        return $result;
    }
    //机器人小智专用天气接口
    public function getweather(){
        $Weather = new Weather();

        //取出缓存数据
        $das= cache('Weather');

        $post = request()->post();
        $kbx_id = $post['city_id'];
        $city = db("city")->where("kbx_id",$kbx_id)->find();
        $city_id = $city['id'];

        if($city_id==91){
            $city_id = 71;//黄石国家公园转向盐湖城
        }

        if (empty($das) || isset($das[$city_id])){
            $Weather->index($city_id);
            $das = cache('Weather');
        }

        $c=[];
        foreach ($das as $key=>$value){
            //判断取出当前查询城市天气数据
            if ($city_id == $key){
                if($value['status']!=='ok'){
                    return json(['msg'=>'没有查询到城市信息','data'=>$value,'code'=>400]);
                }
                //循环天气数据
                foreach ($value['daily_forecast'] as $v){
                    $c[] = [
                        'city_name' => $value['basic']['location'],
                        'city_id' => $value['city_id'],
                        'date' => $v['date'],
                        'cond_code_d' => $v['cond_code_d'],
                        'cond_code_n' => $v['cond_code_n'],
                        'cond_txt_d' => $v['cond_txt_d'],
                        'cond_txt_n' => $v['cond_txt_n'],
                        'tmp_max' => $v['tmp_max'],
                        'tmp_min' => $v['tmp_min'],
                        'hum' => isset($v['hum']),
                        'pcpn' => isset($v['pcpn']),
                        'pop' => isset($v['pop']),
                    ];
                }
                break;
            }
        }
        //判断是否有数据
        if (!empty($c)){
            return json(['msg'=>'查询成功','data'=>$c,'code'=>0]);
        }else{
            return json(['msg'=>'没有查询到城市信息','data'=>$c,'code'=>400]);
        }
    }

    public function checAuth($post)
    {
        //验证鉴权
        $match_arr = array(
            "secret",
            "secret_code"
        );
        $match_res = $this->match_post($match_arr,$post);
        if($match_res['code']==200){
            if(!$this->ApiValidate($post['secret_code'],$post['secret'])){
                //鉴权失败
                return false;
            }else{
                return true;
            }
        }

        return $match_res;
    }
    //产品推荐列表
    public function hotSearchProductList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $list = db::name("product")
            ->field("id,name,item_num as code,start_city,is_default,budget_price as estimatedPrice,ota_price_out as otaSlackPrice,ota_price_busy as otaBusyPrice,supplier_id,supplier_item_code,high_end_vehicle")
            ->where(['search_times'=>['gt',0]])
            ->order('search_times desc,id desc')
            ->limit(20)
            ->select();
        if(empty($list)){
            return json(['msg'=>'列表为空','code'=>400]);
        }else{
            $model = new GT();
            foreach ($list as $key=>$value){
                //查询城市
                $list[$key]['kbxCityId'] = '';
                if(empty($value['is_default']) && !empty($value['start_city'])){
                    $city = db('city')->find($value['start_city']);
                    if(!empty($city)) $list[$key]['kbxCityId'] = $city['kbx_id']??'';
                }
                //查询线路
                $trip = $model->getTripData($value['id']);
                $lineSummary = $model->getTripSummary($trip);
                $list[$key]['toursLineTitle'] = implode("\n",$lineSummary);
                //查询门票
                $poiModel = new Poi();
                $ticketData = $poiModel->getProductTicket($value['id']);
                $list[$key]['ticket'] = $ticketData;
                unset($list[$key]['is_default'],$list[$key]['start_city']);
                $notice = [];
                if(!empty($value['id'])){
                    $notice = db('product_notice')
                        ->field('pick_up_address_json,assemble_address_json,assemble_address_img')
                        ->find($value['id']);
                    $notice = empty($notice)?[]:$notice;
                    $notice = $this->formatProductNotice($notice);
                }
                $list[$key]['notice'] = $notice;
            }
            return json(['msg'=>'查询成功','data'=>$list,'code'=>200]);
        }

    }

    //产品查询
    public function searchProductByCode()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        if(empty($post['code'])){
            return json(['msg'=>'缺省code参数','code'=>400]);
        }else{
            $list = db::name("product")
                ->field("id,name,item_num as code,start_city,is_default,budget_price as estimatedPrice,ota_price_out as otaSlackPrice,ota_price_busy as otaBusyPrice,supplier_id,supplier_item_code,high_end_vehicle")
                ->where(['item_num'=>$post['code']])
                ->limit(20)
                ->select();
            if(empty($list)){
                return json(['msg'=>'列表为空','code'=>400]);
            }else{
                $model = new GT();
                foreach ($list as $key=>$value){
                    //查询城市
                    $list[$key]['kbxCityId'] = '';
                    if(empty($value['is_default']) && !empty($value['start_city'])){
                        $city = db('city')->find($value['start_city']);
                        if(!empty($city)) $list[$key]['kbxCityId'] = $city['kbx_id']??'';
                    }
                    $trip = $model->getTripData($value['id']);
                    $lineSummary = $model->getTripSummary($trip);
                    $list[$key]['toursLineTitle'] = implode("\n",$lineSummary);
                    db('product')->where('id',$value['id'])->setInc('search_times',1);
                    //查询门票
                    $poiModel = new Poi();
                    $ticketData = $poiModel->getProductTicket($value['id']);
                    $list[$key]['ticket'] = $ticketData;
                    unset($list[$key]['is_default'],$list[$key]['start_city']);
                    $notice = [];
                    if(!empty($value['id'])){
                        $notice = db('product_notice')
                            ->field('pick_up_address_json,assemble_address_json,assemble_address_img')
                            ->find($value['id']);
                        $notice = empty($notice)?[]:$notice;
                        $notice = $this->formatProductNotice($notice);
                    }
                    $list[$key]['notice'] = $notice;
                }
                return json(['msg'=>'查询成功','data'=>$list,'code'=>200]);
            }
        }
    }

    //viator 商品提醒配置
    public function viatorGoodsNotice()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $code = $post['viatorCode']??"";
        if(empty($code)){
            return json(['msg'=>'缺省viatorCode参数','code'=>400]);
        }else{
            //检查viator商品
            $goods_where['show'] = 2;
            if(strpos($code,'kbxv')!==false){
                $goods_where['goods_tcode'] = $code;
            }else{
                $goods_where['code'] = $code;
            }
            $viatorGoods = db('goods')->where($goods_where)->find();
            if(empty($viatorGoods)) return json(['msg'=>'暂无该viatorCode的viator商品','code'=>400]);
            //获取viator商品提醒配置的集合地址 集合地址图片 行程信息提醒
            $notice = db('goods_notice')->field('pick_up_address_json,assemble_address_json,assemble_address_img,trip_notice')
                ->where('goods_id',$viatorGoods['goods_id'])
                ->find();
            if(empty($notice)) return json(['msg'=>'暂无提醒配置','code'=>400]);
            $notice = $this->formatProductNotice($notice);
        }

        return json(['msg'=>'查询成功','data'=>$notice,'code'=>200]);
    }
    //格式化提醒信息
    public function formatProductNotice($data)
    {
        if(empty($data)) return [];
        $data['pickUpAddress'] = empty($data['pick_up_address_json'])?[]:
            json_decode($data['pick_up_address_json'],true);
        $data['assembleAddress'] = empty($data['assemble_address_json'])?[]:
            json_decode($data['assemble_address_json'],true);

//        $data['assembleAddressImg'] = empty($data['assemble_address_img'])?[]:
//            explode(',',$data['assemble_address_img']);
        unset($data['pick_up_address_json'],$data['assemble_address_json'],
            $data['assemble_address_img']);
        return $data;
    }
    //按照手机号查询司导
    public function getDriverByTel($name){
        $list['name'] = $name;
        if($list['name']==''){
            return [];
        }
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/drivers/getClientDriverByName';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res=$kbxToken->post_data($url,json_encode($list),$token);
        $res = json_decode($res, true);
        $res=$kbxToken->object_array($res);

        return $res;
    }

    //从订单系统获取机场
    public function kbxGetAirport($city_id)
    {
        $data = [];
        if(isset($city_id) && $city_id>0){
            $city = db("city")->where("id",$city_id)->field("kbx_id")->find();
            $kbxToken = new KbxToken();
            $url = $kbxToken->url.'/cities/'.$city['kbx_id'].'/airports';
            $token = 'Bearer ' . $kbxToken->kbxToken();
            $res = $kbxToken->get_data($url, $token);
            $data = $kbxToken->object_array($res);
        }

        return $data;
    }

    //查询全部订单来源列表
    public function kbx_origin_list()
    {
        return [
            'fliggy'=>'飞猪',
            'mafengwo'=>'马蜂窝',
            'ctrip'=>'携程',
            'toB'=>'toB',
            'other'=>'其它',
            'web-PC'=>'自有线上-官网PC',
            'web-Mob'=>'自有线上-官网移动',
            'WechatOA'=>'自有线上-微信服务号',
            'app'=>'自有线上-App',
            'cmb'=>'自有线上-招行',
            'mxtrip'=>'自有线上-梦想旅行',
            'fxtrip'=>'自有线上-发现之旅',
            'kbx-fliggy'=>'自有线下-飞猪',
            'kbx-mafengwo'=>'自有线下-马蜂窝',
            'kbx-ctrip'=>'自有线下-携程',
            'kbx-Offline'=>'自有线下-快帮行',
        ];
    }

    //20191119 新增定制管理员账号同步
    //新增/更新 合作商定制师
    public function syncAccountCustomMade()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $account = $post['account']??"";
        $company = $post['company']??"";
        $company_id = $post['agentId']??"";
        if(empty($account)) return json_encode(['code'=>400,'msg'=>'缺少账号信息']);
        if(empty($company)) return json_encode(['code'=>400,'msg'=>'缺少公司名称']);
        if(empty($company_id)) return json_encode(['code'=>400,'msg'=>'缺少公司ID']);
        //查询是否已经存在
        $admin = db('admin')->field('id,name')->where(['admin_cate_id'=>28,'name'=>$account])->find();
        if(!empty($admin)) return json_encode(['code'=>401,'msg'=>'合作定制师账号已存在']);
        $res = db('admin')->insert([
            'nickname'=>$company,
            'name'=>$account,
            'password'=>md5(time()),
            'thumb'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
            'admin_cate_id'=>28,
            'company_id'=>$company_id
        ]);

        if($res){
            $admin_id = db()->getLastInsID();
            return json_encode([
                'code'=>200,
                'msg'=>'创建成功',
                'data'=>[
                    'id'=>$admin_id,
                    'account'=>$account,
                    'company'=>$company,
                    'company_id'=>$company_id
                ]
            ]);
        }else{
            return json_encode(['code'=>400,'msg'=>'新增合作定制师失败']);
        }
    }
    //验证TOB账户的登陆状态
    public function getAdminInfoByToken($post_data)
    {
        $kbxToken = new KbxToken();
        $url = $kbxToken->bSellerBackendUrl.'/agent/verifyToken';
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $data = json_encode($post_data);
        $res = $kbxToken->post_data($url, $data,$token);
        log::log('url:'.$url);
        log::log('data:'.$data);
        log::log('token:'.$token);
        log::log('res:'.$res);
        $data = $kbxToken->object_array($res);
        $data = json_decode($data,true);
        //验证接口是否返回正确
        if(empty($data['code']) || empty($data['msg']) || $data['code']!=200 ){
            $data = $data['msg']??"invalid token !";
        }
        return $data;
    }

    //20191126 wtt
    //根据管理员信息获取定制列表
    public function getCustomMadeListByAccount()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //获取所有账号信息
        $company_id = $post['agentId']??0;
        if(empty($company_id)) return json_encode(['code'=>400,'msg'=>'缺少agentId']);
        $adminList = db('admin')->where(['company_id'=>$company_id])->column('id');
        if(empty($adminList)) return json_encode(['code'=>201,'msg'=>'列表为空']);
        //查询是否已经存在
        //分页
        $where = [];
        $qurey_where = function ($qurey) use ($adminList){
            $qurey->where(['t.adminid'=>['in',$adminList]]);
//                ->whereOr('t.is_template',1);
        };
        if(!empty($post['keyword'])) $where['t.name|c.name|a.name'] = ['like','%'.$post['keyword'].'%'];
//        if(!empty($post['isTemplate'])) $where['t.is_template'] = 1;
        $where['t.is_template'] = 0;
        $page = $post['page']??1;
        $field = "t.id,t.name,t.days,t.citys,t.start_city,t.people,t.adult,t.child,t.is_template,
                FROM_UNIXTIME(t.create_time) as create_time,FROM_UNIXTIME(t.start_go_time,'%Y-%m-%d') as start_go_time,
                c.name as start_city_name,a.name as custom_designer";//需要获取的字段
        $pageSize = $post['pageSize']??10;
        $pageCount = db('trip t')
            ->join('city c','c.id=t.start_city','left')
            ->join('admin a','a.id=t.adminid','left')
            ->where($where)
            ->where($qurey_where)
            ->count();
        $tripList = db('trip t')
            ->join('city c','c.id=t.start_city','left')
            ->join('admin a','a.id=t.adminid','left')
            ->field($field)
            ->where($where)
            ->where($qurey_where)
            ->order('create_time desc')
            ->page($page,$pageSize)
            ->select();

        $result = [
            'currPage'=>$page,
            'pageSize'=>$pageSize,
            'pageCount'=>$pageCount,
            'maxPage'=>ceil($pageCount/$pageSize),
            'list'=>$tripList
        ];

        return json_encode(['code'=>200,'msg'=>'获取定制列表成功','data'=>$result]);
    }
    //根据管理员信息获取定制模板列表
    public function getCustomMadeTemplateList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        if(!empty($post['keyword'])) $where['t.name|c.name|a.name'] = ['like','%'.$post['keyword'].'%'];
        //模板
        $where['t.is_template'] = 1;
        $field = "t.id,t.name,t.days,t.citys,t.start_city,t.people,t.adult,t.child,t.is_template,
                FROM_UNIXTIME(t.create_time) as create_time,FROM_UNIXTIME(t.start_go_time,'%Y-%m-%d') as start_go_time,
                c.name as start_city_name,a.name as custom_designer";//需要获取的字段
        $tripList = db('trip t')
            ->join('city c','c.id=t.start_city','left')
            ->join('admin a','a.id=t.adminid','left')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->select();

        $result = [
            'list'=>$tripList
        ];

        return json_encode(['code'=>200,'msg'=>'获取定制列表成功','data'=>$result]);
    }
    //删除定制
    public function delCustomMadeByAccount()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //获取所有账号信息
        $id = $post['id']??0;
        $account = $post['account']??'';
        $trip = db('trip')->find($id);
        if(empty($id) || empty($trip)) return json_encode(['code'=>400,'msg'=>'定制行程不存在']);
        $admin = db('admin')->where('name',$account)->find();
        if(empty($account) || empty($admin)) return json_encode(['code'=>400,'msg'=>'账号信息有误']);
        $_admin = db('admin')->find($trip['adminid']);
        if(empty($_admin) || $_admin['company_id']!=$admin['company_id']) return json_encode(['code'=>403,'msg'=>'您无权删除此定制']);

        db::startTrans();
        try{
            $scheduleid = db('schedule')->where('groupid',$id)->column('id');
            if(!empty($scheduleid)){
                $activeid = db('active')->where(['groupid'=>['in',$scheduleid]])->column('id');
                if(!empty($activeid)){
                    db('active')->where(['id'=>['in',$activeid]])->delete();
                }
                db('schedule')->where(['id'=>['in',$scheduleid]])->delete();
            }
            db('trip')->delete($id);

            db::commit();
            return json_encode(['code'=>200,'msg'=>'删除成功']);
        }catch(Exception $e){
            db::rollback();
            return json_encode(['code'=>400,'msg'=>'删除失败']);
        }

    }

    //复制模板生成定制
    public function createCustomMadeByTemplateId()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //获取所有账号信息
        $account = $post['account']??'';
        $admin = db('admin')->where('name',$account)->find();
        if(empty($account) || empty($admin)) return json_encode(['code'=>400,'msg'=>'账号信息有误']);
        $temp_id = $post['temp_id']??0;
        //次数限制条件
        //$time_res = (new TripApiModel())->checkCreateTime($admin['id']);
//        if(!is_array($time_res)){
//            return json_encode(['code'=>400,'msg'=>$time_res]);
//        }
        $result = (new TripApiModel())->createCustomMadeByTemplate($temp_id,$admin['id']);

        if(!is_array($result)){
            return json_encode(['code'=>400,'msg'=>$result]);
        }else{
            $result['code'] = 200;
            return json_encode($result);
        }

    }

    //订单完成推送佣金返现入账
    public function pushConfirmOrderAddMemberMoney()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $personOrderNo = $post['orderNo']??0;
        $result = (new OrderModel())->addPromoteMemberMoneyByConfirmOrder($personOrderNo);
        if(!is_array($result)){
            return json_encode(['code'=>400,'msg'=>$result]);
        }else{
            $result['code'] = 200;
            return json_encode($result);
        }
    }
    //订单出行推送拼友用户计入返现
    public function pushCompleteOrderCashBack()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $orders = $post['orders']??0;
        $result = (new OrderModel())->addExpextMoneyByCompleteGrouptourOrder($orders);
        if(!is_array($result)){
            return json_encode(['code'=>400,'msg'=>$result]);
        }else{
            $result['code'] = 200;
            return json_encode($result);
        }
    }
    //订单完成推送拼友用户返现入账
    public function pushConfirmOrderCashBack()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $orders = $post['orders']??0;
        $result = (new OrderModel())->addMemeberMoneyByConfirmGrouptourOrder($orders);
        if(!is_array($result)){
            return json_encode(['code'=>400,'msg'=>$result]);
        }else{
            $result['code'] = 200;
            return json_encode($result);
        }
    }
    //读取对应的拼团线路的返现规则
    public function getCashBackRulesByLineId($line_id)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $busySeason = $post['busySeason']??false;
        if(empty($busySeason)){
            $package_type = 1;//淡季
            $field = 'currency,person_price,carType,subType,carPrice,unitTicketPrice';
        }else{
            $package_type = 2;//旺季
            $field = 'currency,busy_person_price as person_price,carType,subType,busyCarPrice as carPrice,unitTicketPrice';
        }
        $detail = db('group_tours_line')
            ->field($field)
            ->find($line_id);
        if(empty($line_id) || empty($detail)) return json_encode(['code'=>404,'msg'=>'线路不存在']);
        $detail['subType'] = (new SD())->getSubType($detail['subType']);
        $packages = db('grouptour_package')->where(['grouptour_id'=>$line_id,'package_type'=>$package_type])->select();
        $package_ids = array_column($packages,'id');
        if(empty($package_ids)) return json_encode(['code'=>404,'msg'=>'暂未设置套餐']);
        $specs = db('grouptour_specs')
            ->field('name,num,price')
            ->where(['package_id'=>['in',$package_ids]])
            ->select();
        if(empty($specs)) return json_encode(['code'=>404,'msg'=>'暂未设置规格']);

        $detail['specs'] = $specs;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$detail]);
    }
    //导入文件读取并生成数据
    public function readFileCreateData()
    {
        return 'please open function';exit;
        $file = ROOT_PATH.'agentMember.csv';

        $data = $this->getCSVFileData($file);
//        var_dump(json_encode($data));exit;

        log::log('导入开始');
        foreach ($data as $value){
            $this->createAccount($value);
        }
        log::log('导入结束');
        echo 'success';
    }
    protected function getCSVFileData($file)
    {
        if (!is_file($file)) {
            exit('没有文件');
        }

        $handle = fopen($file, 'r');
        if (!$handle) {
            exit('读取文件失败');
        }
        $dataArray = [];
        while (($data = fgetcsv($handle)) !== false) {
            // 下面这行代码可以解决中文字符乱码问题
            // $data[0] = iconv('gbk', 'utf-8', $data[0]);
            // 跳过第一行标题
            if ($data[0] == '账号') {
                continue;
            }
            // data 为每行的数据，这里转换为一维数组
            //print_r($data);// Array ( [0] => tom [1] => 12 )
            $dataArray[] = $data;
        }

        fclose($handle);

        return $dataArray;
    }

    protected function createAccount($data)
    {
        //查询是否已经存在
        $admin = db('admin')->field('id,name')->where(['admin_cate_id'=>28,'name'=>$data[0]])->find();
        if(!empty($admin)){
            log::log($data[0].' : exist');
            return true;
        }
        $res = db('admin')->insert([
            'nickname'=>$data[2],
            'name'=>$data[0],
            'password'=>md5(time()),
            'thumb'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
            'admin_cate_id'=>28,
            'company_id'=>$data[1]
        ]);

        if($res){
            log::log($data[0].' : success');
        }else{
            log::log($data[0].' : failed');
        }
    }

    //检查访问的次数，防止恶意复制 规则【5分钟最多5条，1小时最多10条，1天最多20条】
    //暂未启用【2019年12月17日】
    public function checkCreateTime($adminid)
    {
        $maxMinTime = 5;
        $maxHourTime = 10;
        $maxDayTime = 20;

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(strtotime('+1 day',$start_time));
        $res = db('trip')
            ->where(['adminid'=>$adminid,'create_time'=>['between',[$start_time,$end_time]]])
            ->field("id,create_time")
            ->select();
        if(empty($res)) return ['code'=>200,'msg'=>'success','data'=>$res];
        if(count($res)>= $maxDayTime){
            return '您每日最多能复制'.$maxDayTime.'次,请明日再试';
        }else{
            $start_hour = strtotime(date('Y-m-d H'));
            $end_hour = strtotime(strtotime('+1 hour',$start_hour));
            $start_min = strtotime(date('Y-m-d H:i'));
            $end_min = strtotime(strtotime('+5 minute',$start_min));
            $hour_time = $min_time = 0;
            foreach ($res as $value){
                if($value['create_time'] >= $start_hour && $value['create_time']<=$end_hour){
                    $hour_time ++;
                }
                if($value['create_time'] >= $start_min && $value['create_time']<=$end_min){
                    $min_time ++;
                }
            }

            if($hour_time > $maxHourTime){
                return '您每小时最多能复制'.$maxHourTime.'次,请稍后再试';
            }

            if($min_time > $maxMinTime){
                return '您每5分钟最多能复制'.$maxMinTime.'次,请稍后再试';
            }
        }

        return ['code'=>200,'msg'=>'success','data'=>$res];
    }

    //通过城市和包车类型获取包车价格
    public function getCarPriceBySubTypeAndCity($post_data)
    {
        $kbxToken = new KbxToken();
        //请求地址
        $url = $kbxToken->url.'/client/priceFactor/getDayPriceFactorByCityIdV2';
        //鉴权字段
        $token = 'Bearer ' . $kbxToken->kbxToken();
        //请求体
        $list = json_encode($post_data);
        //获取结果
        $res = $kbxToken->post_data($url,$list,$token);
        $this->writeCarPriceData($url,$list,$res);
        $res = $kbxToken->object_array($res);
        $res = json_decode($res,true);
        return $res;
    }

    //通过手机号创建用户信息
    public function createMemberBySystemOrder()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $phone = $post['phone']??'';
        $countryCode = $post['countryCode']??'';
        $kbxId = $post['kbxId']??'';
        $member = db('member')->where('kbx_id',$kbxId)->find();
        if(empty($phone)) return json_encode(['code'=>400,'msg'=>'手机号为空']);
        if(!empty($member)){
            $exist_phone = db('member')->where([
                'member_phone'=>$phone,
                'member_id'=>['neq',$member['member_id']]
            ])->find();
            if(!empty($exist_phone)) return json_encode(['code'=>400,'msg'=>'手机号已存在']);
            //更新手机号信息
            $res = db('member')->where('member_id',$member['member_id'])->update([
                'member_phone'=>$phone,
                'country_code'=>$countryCode,
                'updatetime'=>time()
            ]);
            $member_id = $member['member_id'];
        }else{
            $exist_phone = db('member')->where([
                'member_phone'=>$phone
            ])->find();
            if(!empty($exist_phone)){
                $res = db('member')->where('member_id',$exist_phone['member_id'])->update([
                    'kbx_id'=>$kbxId,
                    'updatetime'=>time()
                ]);
                $member_id = $exist_phone['member_id'];
            }else{
                $res = db('member')->insert([
                    'member_username'=>$phone,
                    'country_code'=>$countryCode,
                    'member_type_id'=>1,
                    'member_phone'=>$phone,
                    'member_nickname'=>$phone,
                    'kbx_id'=>$kbxId,
                    'creattime'=>time(),
                    'updatetime'=>time()
                ]);
                $member_id = db()->getLastInsID();
            }
        }

        if($res!==false){
            return json_encode(['code'=>200,'msg'=>'同步用户成功','data'=>['member_id'=>$member_id]]);
        }else{
            return json_encode(['code'=>400,'msg'=>'手机号为空']);
        }
    }

    //判断是否为淡旺季
    public function isBusySeasonByDate($post_data)
    {
        $kbxToken = new KbxToken();
        //请求地址
        $url = $kbxToken->url.'/client/priceFactor/isBusySeasonV2';
        //鉴权字段
        $token = 'Bearer ' . $kbxToken->kbxToken();
        //请求体
        $list = json_encode($post_data);
        //获取结果
        $res = $kbxToken->post_data($url,$list,$token);
        $res = $kbxToken->object_array($res);
        $res = json_decode($res,true);
        return $res;
    }

    //全量产品查询 没有搜索条件返回空
    public function getProListBySearchParam()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return $this->result('鉴权失败',[],400,'json');
        }
        $where = [];
        //搜索条件 1城市2产品类型3供应商
        if(!empty($post['cityId'])){
            //查找当前城市
            $city = db('city')->where('kbx_id',$post['cityId'])->find();
            if(empty($city)) return $this->result('订单系统暂未补录该城市',[],400,'json');
            $where['start_city'] = $city['id'];
        }
        if(!empty($post['serviceType'])){
            //查找当前城市
            $service_type = db('service_type')->where('type',$post['serviceType'])->find();
            if(empty($service_type)) return $this->result('暂不支持的服务类型',[],400,'json');
            $where['service_type'] = $service_type['id'];
        }
        if(!empty($post['supplierId'])) $where['supplier_id'] = $post['supplierId'];
        if(!empty($post['productCode'])) $where['item_num'] = ['like','%'.$post['productCode'].'%'];
        $orderBy = empty($where)?'search_times desc':'id desc';
        $list = db::name("product")
            ->field("id,name,item_num as code,start_city,is_default,
            budget_price as estimatedPrice,ota_price_out as otaSlackPrice,
            ota_price_busy as otaBusyPrice,supplier_id,supplier_item_code,
            high_end_vehicle")
            ->where($where)
            ->limit(20)
            ->order($orderBy)
            ->select();
//        var_dump(db()->getLastSql());exit;

        if(empty($list)){
            return $this->result('列表为空',[],400,'json');
        }else{
            $model = new GT();
            foreach ($list as $key=>$value){
                //查询城市
                $list[$key]['kbxCityId'] = '';
                if(empty($value['is_default']) && !empty($value['start_city'])){
                    $city = db('city')->find($value['start_city']);
                    if(!empty($city)) $list[$key]['kbxCityId'] = $city['kbx_id']??'';
                }
                //查询线路
                $trip = $model->getTripData($value['id']);
                $lineSummary = $model->getTripSummary($trip);
                $list[$key]['toursLineTitle'] = implode("\n",$lineSummary);
                //查询门票
                $poiModel = new Poi();
                $ticketData = $poiModel->getProductTicket($value['id']);
                $list[$key]['ticket'] = $ticketData;
                unset($list[$key]['is_default'],$list[$key]['start_city']);
            }

            return $this->result('success',$list,200,'json');
        }
    }

    //通过产品code查询产品详情
    public function getProductInfoByCode()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return $this->result('鉴权失败',[],400,'json');
        }
        if(empty($post['goods']['code'])) return $this->result('缺少参数productCode',[],400,'json');
        $where['item_num'] = $post['goods']['code'];
        $result = db::name("product")
            ->field("id as productId,name,item_num as productCode,start_city,is_default,
            budget_price as estimatedPrice,ota_price_out as otaSlackPrice,
            ota_price_busy as otaBusyPrice,supplier_id,supplier_item_code,
            high_end_vehicle,supplier_admin_id")
            ->where($where)
            ->find();

        if(empty($result)){
            return $this->result('暂未查询到该产品',[],400,'json');
        }else{
            $model = new GT();

            //查询城市
            $result['kbxCityId'] = '';
            if(empty($result['is_default']) && !empty($result['start_city'])){
                $city = db('city')->find($result['start_city']);
                if(!empty($city)) $result['kbxCityId'] = $city['kbx_id']??'';
            }
            //查询线路
            $trip = $model->getTripData($result['productId']);
            $lineSummary = $model->getTripSummary($trip);
            $result['toursLineTitle'] = implode("\n",$lineSummary);
            //查询门票
            $poiModel = new Poi();
            $ticketData = $poiModel->getProductTicket($result['productId']);
            $result['ticket'] = $ticketData;
            unset($result['is_default'],$result['start_city']);
            //获取套餐信息
            $personList = [];
            if(!empty($post['orderPerson'])){
                $personList = $this->getPersonListByOrderPerson($post['orderPerson'],$post['travelTime']??'');
            }
            return $this->result('success',['goods'=>$result,'orderPerson'=>$personList],200,'json');
        }
    }

    public function getPersonListByOrderPerson($orderPerson=[],$travelTime="")
    {
        if(empty($orderPerson) || !is_array($orderPerson)) return [];
        $supplierCost = [];
        $personIds = array_column($orderPerson,'person_id');
        if(empty($personIds)) return [];
        $supplierCost = db('product_dailyprice')
            ->field('id as person_id,time,product_id,package_id,specs_id,name,price as cost')
            ->where([
                'id'=>['in',$personIds]
            ])->select();

        foreach ($supplierCost as $key=>$value){
            foreach ($orderPerson as $person){
                if($value['person_id']==$person['person_id']){
                    $supplierCost[$key]['person_nm_buy'] = $person['person_num_buy']??0;
                    break;
                }
            }
        }
        return $supplierCost;
    }

}